import java.io.*;

public class DirCopyDemo02 {
    public static void main(String[] args) {
        String from = "C:\\Users\\Administrator\\Desktop\\1";

        String to = "C:\\Users\\Administrator\\Desktop\\test";
        copyDir(from, to);
    }

    public static void copyDir(String from, String to) {
        File f = new File(from);
        File t = new File(to);
        if (!t.exists()) {
            t.mkdirs();
        }

        File[] files = f.listFiles();//[2.txt,3]
        for (File file : files) {
            String fromPath = from + File.separator + file.getName();//C:\\Users\\Administrator\\Desktop\\1\\3
            String toPath = to + File.separator + file.getName();//C:\\Users\\Administrator\\Desktop\\test\\2\\3
            if (file.isFile()) {
//                copyFile("C:\\Users\\Administrator\\Desktop\\1\\1.txt","C:\\Users\\Administrator\\Desktop\\test\\1.txt");
                copyFile(fromPath, toPath);
            }else{
                copyDir(fromPath,toPath);
            }
        }
    }


    public static void copyFile(String f, String t) {
        FileInputStream input = null;
        FileOutputStream output = null;

        try {
            input = new FileInputStream(f);// 输入流
            output = new FileOutputStream(t);// 输出流
            int len;
            byte[] bytes = new byte[1024];
            while ((len = input.read(bytes)) != -1) {
                output.write(bytes, 0, len);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (output != null) {
                try {
                    output.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
